<template>
  <view class="member-list-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="navigateBack">
        <image class="back-icon" src="/static/Images/shop/Fanhuih.png" mode="aspectFit"></image>
      </view>
      <view class="title">我的团队</view>
    </view>
    
    <!-- 标签切换 -->
    <view class="tab-container">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'direct' }" 
        @click="switchTab('direct')"
      >
        我的直推
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'indirect' }" 
        @click="switchTab('indirect')"
      >
        团队间推
      </view>
      <view class="tab-indicator" :style="indicatorStyle"></view>
    </view>
    
    <!-- 会员列表 -->
    <scroll-view scroll-y class="member-list">
      <view class="member-item" v-for="(member, index) in filteredMembers" :key="index">
        <image class="member-avatar" :src="member.avatar" mode="aspectFill"></image>
        <view class="member-info">
          <view class="member-nick-name">
            <view class="member-name">{{ member.name }}</view>
            <view class="referrer-name" v-if="member.type === 'indirect' && member.referrerSid">
              <text class="referrer-chip">推荐人: {{ member.referrerName || member.referrerSid }}</text>
            </view>
          </view>
          
          <view class="member-id">加入时间: {{ member.joinTime }}</view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredMembers.length === 0">
        <image class="empty-icon" src="/static/Images/touxiang/1.png" mode="aspectFit"></image>
        <view class="empty-text">暂无团队成员</view>
      </view>
    </scroll-view>
    
    <!-- 底部指示器 -->
    <view class="bottom-indicator"></view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { userApi } from '@/utils/api';

// 当前激活的标签
const activeTab = ref('direct');

// 标签指示器样式
const indicatorStyle = computed(() => ({
  transform: activeTab.value === 'direct' ? 'translateX(0)' : 'translateX(100%)'
}));

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
  // 切换标签后根据当前标签重新拉取对应类型的数据
  fetchTeamMembers(1, 10);
};

// 返回上一页
const navigateBack = () => {
  uni.navigateBack();
};

// 成员数据（来自接口）
const members = ref([]);

// 直推成员(id->昵称)映射，用于间推成员的“推荐人”展示
const directNameById = ref({});

// 工具：清洗头像 URL（去掉反引号和多余引号）
const sanitizeAvatar = (url) => {
  if (!url) return '';
  let s = String(url).replace(/`/g, '').trim();
  if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith('\'') && s.endsWith('\''))) {
    s = s.slice(1, -1).trim();
  }
  return s;
};

// 工具：格式化时间戳（秒）
const formatTimestamp = (ts) => {
  if (!ts) return '';
  const d = new Date(Number(ts) * 1000);
  const pad = (n) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
};

// 加载直推(id->昵称)映射
const buildDirectNameMap = async () => {
  try {
    const res = await userApi.myTeamList(1, 1000, 0); // 直推=0
    const raw = res?.data ?? [];
    const list = Array.isArray(raw) ? raw : (Array.isArray(raw?.list) ? raw.list : []);
    const map = {};
    list.forEach(item => {
      const id = item?.id;
      const name = item?.nick_name || item?.real_name || '昵称';
      if (id != null) map[id] = name;
    });
    directNameById.value = map;
  } catch (e) {
    console.error('加载直推映射失败：', e);
    directNameById.value = {};
  }
};

// 获取团队成员列表（默认 page=1, size=10）
const fetchTeamMembers = async (page = 1, size = 10) => {
  try {
    // 根据当前标签确定 type：直推=0，间推=1
    const typeVal = activeTab.value === 'direct' ? 0 : 1;

    // 如果是间推列表，需要先准备直推映射
    if (typeVal === 1 && Object.keys(directNameById.value).length === 0) {
      await buildDirectNameMap();
    }

    const res = await userApi.myTeamList(page, size, typeVal);
    const raw = res?.data ?? [];
    const list = Array.isArray(raw) ? raw : (Array.isArray(raw?.list) ? raw.list : []);
    const filtered = list.filter(item => item && item.top_id !== item.id);
    members.value = filtered.map(item => ({
      id: item.id,
      avatar: sanitizeAvatar(item.avatar),
      name: item.nick_name || item.real_name || '昵称',
      joinTime: formatTimestamp(item.create_time),
      // 成员类型与当前激活的标签保持一致，便于前端筛选逻辑
      type: activeTab.value,
      // 推荐人：取成员 sid，并在直推映射中查找昵称
      referrerSid: item.sid,
      referrerName: item.sid ? (directNameById.value[item.sid] || '') : ''
    }));
  } catch (e) {
    console.error('获取团队列表失败：', e);
    members.value = [];
    uni.showToast({ title: e.message || '加载失败', icon: 'none' });
  }
};

onMounted(() => {
  fetchTeamMembers(1, 10);
});

// 根据标签筛选会员
const filteredMembers = computed(() => {
  return members.value.filter(member => member.type === activeTab.value);
});
</script>

<style lang="scss">
.member-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-bottom: 30rpx;
}

/* 顶部导航栏 */
.header {
  position: relative;
  display: flex;
  align-items: center;
  padding: 80rpx 30rpx 20rpx;
  background-color: #fff;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  margin-right: 60rpx; /* 为了平衡左侧返回按钮的宽度 */
}

/* 标签切换 */
.tab-container {
  display: flex;
  position: relative;
  background-color: #fff;
  padding: 0 30rpx 20rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  color: #666;
  padding: 20rpx 0;
  position: relative;
  transition: color 0.3s;
}

.tab-item.active {
  color: #ff4d4f;
  font-weight: 500;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50%;
  height: 4rpx;
  background-color: #ff4d4f;
  transition: transform 0.3s;
}

/* 会员列表 */
.member-list {
  height: calc(100vh - 240rpx);
  padding: 20rpx 30rpx;
}

.member-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.member-avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.member-info {
  flex: 1;
}

.member-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 10rpx;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

/* 新增：昵称与推荐人左右分布 */
.member-nick-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
}

/* 调整：推荐人容器靠右显示，不再依赖大 margin 左移 */
.referrer-name {
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
  margin-right: 0.5rem;
}

/* 将徽章样式放在具体的文字元素上，避免影响容器布局 */
.referrer-chip {
  font-size: 24rpx;
  color: #666;
  font-weight: normal;
  background-color: #f0f0f0;
  padding: 4rpx 12rpx;
  border-radius: 1.5rem;
}

.member-id {
  font-size: 26rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 底部指示器 */
.bottom-indicator {
  width: 120rpx;
  height: 8rpx;
  background-color: #ddd;
  border-radius: 4rpx;
  margin: 30rpx auto;
}
</style>